<template>
  <div class="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
    <div class="sm:mx-auto sm:w-full sm:max-w-md">
      <div class="text-center">
        <h2 class="text-3xl font-bold text-gray-900">重置密码</h2>
        <p class="mt-2 text-sm text-gray-600">
          输入你的邮箱地址，我们将发送重置链接给你
        </p>
      </div>
    </div>

    <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
      <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
        <!-- 步骤1: 输入邮箱 -->
        <div v-if="step === 1">
          <form class="space-y-6" @submit.prevent="sendResetEmail">
            <div>
              <label for="email" class="block text-sm font-medium text-gray-700">
                邮箱地址
              </label>
              <div class="mt-1">
                <input
                  id="email"
                  v-model="form.email"
                  name="email"
                  type="email"
                  autocomplete="email"
                  required
                  class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                  placeholder="请输入注册时的邮箱地址"
                />
              </div>
              <p v-if="errors.email" class="mt-1 text-sm text-red-600">{{ errors.email }}</p>
            </div>

            <!-- 错误信息 -->
            <div v-if="error" class="bg-red-50 border border-red-200 rounded-md p-4">
              <div class="flex">
                <svg class="h-5 w-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <div class="ml-3">
                  <h3 class="text-sm font-medium text-red-800">发送失败</h3>
                  <div class="mt-2 text-sm text-red-700">{{ error }}</div>
                </div>
              </div>
            </div>

            <!-- 提交按钮 -->
            <div>
              <button
                type="submit"
                :disabled="isLoading"
                class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <svg
                  v-if="isLoading"
                  class="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                {{ isLoading ? '发送中...' : '发送重置链接' }}
              </button>
            </div>
          </form>
        </div>

        <!-- 步骤2: 确认邮件已发送 -->
        <div v-else-if="step === 2" class="text-center">
          <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100">
            <svg class="h-6 w-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
            </svg>
          </div>
          <h3 class="mt-4 text-lg font-medium text-gray-900">邮件已发送</h3>
          <p class="mt-2 text-sm text-gray-600">
            我们已向 <strong>{{ form.email }}</strong> 发送了密码重置链接
          </p>
          <p class="mt-2 text-sm text-gray-600">
            请检查你的邮箱（包括垃圾邮件文件夹），点击链接重置密码
          </p>
          <div class="mt-6">
            <button
              type="button"
              class="text-blue-600 hover:text-blue-500 text-sm font-medium"
              @click="resendEmail"
            >
              没有收到邮件？重新发送
            </button>
          </div>
          <div class="mt-4">
            <router-link
              to="/login"
              class="text-blue-600 hover:text-blue-500 text-sm font-medium"
            >
              返回登录页面
            </router-link>
          </div>
        </div>

        <!-- 步骤3: 重置密码 -->
        <div v-else-if="step === 3">
          <form class="space-y-6" @submit.prevent="resetPassword">
            <div>
              <label for="newPassword" class="block text-sm font-medium text-gray-700">
                新密码
              </label>
              <div class="mt-1 relative">
                <input
                  id="newPassword"
                  v-model="form.newPassword"
                  name="newPassword"
                  :type="showNewPassword ? 'text' : 'password'"
                  autocomplete="new-password"
                  required
                  class="appearance-none block w-full px-3 py-2 pr-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                  placeholder="请输入新密码"
                />
                <button
                  type="button"
                  class="absolute inset-y-0 right-0 pr-3 flex items-center"
                  @click="showNewPassword = !showNewPassword"
                >
                  <svg
                    v-if="showNewPassword"
                    class="h-5 w-5 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21"></path>
                  </svg>
                  <svg
                    v-else
                    class="h-5 w-5 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                  </svg>
                </button>
              </div>
              <p v-if="errors.newPassword" class="mt-1 text-sm text-red-600">{{ errors.newPassword }}</p>
              <div class="mt-1 text-sm text-gray-500">
                密码长度至少8位，包含字母和数字
              </div>
            </div>

            <div>
              <label for="confirmNewPassword" class="block text-sm font-medium text-gray-700">
                确认新密码
              </label>
              <div class="mt-1 relative">
                <input
                  id="confirmNewPassword"
                  v-model="form.confirmNewPassword"
                  name="confirmNewPassword"
                  :type="showConfirmNewPassword ? 'text' : 'password'"
                  autocomplete="new-password"
                  required
                  class="appearance-none block w-full px-3 py-2 pr-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                  placeholder="请再次输入新密码"
                />
                <button
                  type="button"
                  class="absolute inset-y-0 right-0 pr-3 flex items-center"
                  @click="showConfirmNewPassword = !showConfirmNewPassword"
                >
                  <svg
                    v-if="showConfirmNewPassword"
                    class="h-5 w-5 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21"></path>
                  </svg>
                  <svg
                    v-else
                    class="h-5 w-5 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                  </svg>
                </button>
              </div>
              <p v-if="errors.confirmNewPassword" class="mt-1 text-sm text-red-600">{{ errors.confirmNewPassword }}</p>
            </div>

            <!-- 错误信息 -->
            <div v-if="error" class="bg-red-50 border border-red-200 rounded-md p-4">
              <div class="flex">
                <svg class="h-5 w-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <div class="ml-3">
                  <h3 class="text-sm font-medium text-red-800">重置失败</h3>
                  <div class="mt-2 text-sm text-red-700">{{ error }}</div>
                </div>
              </div>
            </div>

            <!-- 提交按钮 -->
            <div>
              <button
                type="submit"
                :disabled="isLoading"
                class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <svg
                  v-if="isLoading"
                  class="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                {{ isLoading ? '重置中...' : '重置密码' }}
              </button>
            </div>
          </form>
        </div>

        <!-- 步骤4: 重置成功 -->
        <div v-else-if="step === 4" class="text-center">
          <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100">
            <svg class="h-6 w-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
            </svg>
          </div>
          <h3 class="mt-4 text-lg font-medium text-gray-900">密码重置成功</h3>
          <p class="mt-2 text-sm text-gray-600">
            你的密码已成功重置，现在可以使用新密码登录了
          </p>
          <div class="mt-6">
            <router-link
              to="/login"
              class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              返回登录页面
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const step = ref(1)
const form = reactive({
  email: '',
  newPassword: '',
  confirmNewPassword: ''
})

const showNewPassword = ref(false)
const showConfirmNewPassword = ref(false)
const isLoading = ref(false)
const error = ref('')
const errors = reactive({
  email: '',
  newPassword: '',
  confirmNewPassword: ''
})

// 验证方法
const validateEmail = () => {
  errors.email = ''
  if (!form.email) {
    errors.email = '请输入邮箱地址'
    return false
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
    errors.email = '请输入有效的邮箱地址'
    return false
  }
  return true
}

const validatePassword = () => {
  errors.newPassword = ''
  errors.confirmNewPassword = ''

  if (!form.newPassword) {
    errors.newPassword = '请输入新密码'
    return false
  }
  if (form.newPassword.length < 8) {
    errors.newPassword = '密码至少8个字符'
    return false
  }
  if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(form.newPassword)) {
    errors.newPassword = '密码必须包含字母和数字'
    return false
  }

  if (!form.confirmNewPassword) {
    errors.confirmNewPassword = '请确认新密码'
    return false
  }
  if (form.newPassword !== form.confirmNewPassword) {
    errors.confirmNewPassword = '两次输入的密码不一致'
    return false
  }

  return true
}

// 方法
const sendResetEmail = async () => {
  if (!validateEmail()) {
    return
  }

  isLoading.value = true
  error.value = ''

  try {
    await authStore.sendResetPasswordEmail(form.email)
    step.value = 2
  } catch (err: any) {
    error.value = err.message || '发送失败，请重试'
  } finally {
    isLoading.value = false
  }
}

const resendEmail = async () => {
  await sendResetEmail()
}

const resetPassword = async () => {
  if (!validatePassword()) {
    return
  }

  isLoading.value = true
  error.value = ''

  try {
    const token = route.query.token as string
    if (!token) {
      throw new Error('无效的重置链接')
    }

    await authStore.resetPassword({
      token,
      newPassword: form.newPassword
    })

    step.value = 4
  } catch (err: any) {
    error.value = err.message || '重置失败，请重试'
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  // 检查是否有重置token
  const token = route.query.token
  if (token) {
    step.value = 3
  }
})
</script>
